<?php
class Login extends CI_Controller{
    function  __construct(){
        parent::__construct();
        $this->load->library(array('form_validation','session','user_libs'));
        $this->load->helper(array( 'url','form'));
        if($this->user_libs->isLogin() && $this->user_libs->isAdmin()){
            redirect(base_url().'backend/home');
            exit();
        }
    }
    function index(){
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|md5|xss_clean');
        if($this->form_validation->run() == false)
            $this->load->view('backend/user/login');
        else{
            $u = $this->input->post('username');
            $p = $this->input->post('password');
            
            $user = $this->user_model->checkUser($u,$p);
            if ($user){
                if($user['active'] == 0){
                    $data['error'] = 'Tài khoản đã bị khóa.';
                    $this->load->view('backend/user/login',$data);
                }else{
                    $data = array(
                        'username'   => $user['username'],
                        'userid'     => $user['userid'],
                        'password'   => $user['password'],
                        'level'      => $user['level']
                    );
                    $this->session->set_userdata($data);
                    redirect(base_url().'backend/user');
                    exit;
                }
            }else{
                $this->load->view('backend/user/login',array('error' => 'Username hoac mat khau khong dung'));
            }
        }
    }
     
}